package com.summerrain.colnect.jsouplib;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;

import org.jsoup.Jsoup;
import org.jsoup.Connection.Response;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class GetCountries {
	
	public static ArrayList<String> getCountriesByCatgType(String catgType) {
		ArrayList<String> data = new ArrayList<String>();
		try {
			long lStartTime = new Date().getTime(); // start time
			Response response = Jsoup
					.connect(
							"http://colnect.com/en/"+catgType+"/countries")
					.userAgent(
							"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.21 (KHTML, like Gecko) Chrome/19.0.1042.0 Safari/535.21")
					.timeout(10000).execute();
			long lEndTime = new Date().getTime(); // end time
			System.out.println("Elapsed milliseconds: "
					+ (lEndTime - lStartTime));
			String resp = response.body();
			Document doc = Jsoup.parse(resp);
			Elements pngs = doc.select("img[src$=.png]");	
			
			System.out.println("title " + doc.title());
			int ctr = 0;
			for (Element src : pngs) {
				String tmp = "";
				if(src.attr("src").contains("http://i.colnect.net/images/flag/") || src.attr("src").contains("http://i.colnect.net/images/flags/"))
				{
				//System.out.print("Image Path:"+src.attr("src")+" Link href: "+(src.parent()).attr("href"));
				//tmp = "Image Path:"+src.attr("src")+" Link href: "+(src.parent()).attr("href") +"|"; 
				 tmp = src.attr("src")+"@"+(src.parent()).attr("href") +"@"+(((src.parent()).attr("title")).replace("Stamps:","")).trim()+"@";
				if(src.parent().nextElementSibling() != null)
				{
				//System.out.println(" count: "+(src.parent().nextElementSibling()).text());
				tmp += (src.parent().nextElementSibling()).text();
				}
				else
				{
					//System.out.println(" count: "+((src.parent().nextSibling().toString()).replace('(', ' ')).replace(')', ' ').trim());
					tmp += ((src.parent().nextSibling().toString()).replace('(', ' ')).replace(')', ' ').trim();
				}
				ctr++;
				data.add(tmp);
				}
			}
			System.out.println("size: "+pngs.size()+" final val: "+ctr);
			long displayTime = new Date().getTime(); // end time
			System.out.println("display milliseconds: "+ (displayTime - lEndTime));

		} catch (IOException e) {
			e.printStackTrace();
		}
		return data;

	}
}
